#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 ZHENG Zhong <heavyzheng nospam-at gmail D0T com>
# - http://heavyz.blogspot.com/
# - http://buggarden.blogspot.com/
#
# Ajax actions for the Foods N' Roses webapp.
#
# Created on 2008-11-05.
# $Id$
#

from django.http import HttpRequest

from buggarden.apps.fnr import utils

from buggarden.apps.fnr.config import Config
from buggarden.apps.fnr.models import Resto
from buggarden.apps.fnr.models import RestoComment


#---------------------------------------------------------------------------------------------------
# AJAX exception class and base action class
#---------------------------------------------------------------------------------------------------


class AjaxError(Exception):
    
    def __init__(self, message=None):
        super(AjaxError, self).__init__(message)


class AjaxAction(object):

    def process(self, context_dict, request):
        if request is None:
            raise AjaxError("Failed to prcess a None request.")
        elif request.method == "GET":
            self.get(context_dict, request)
        elif request.method == "POST":
            self.post(context_dict, request)
        else:
            raise AjaxError("Request method '%s' not supported." % request.method)

    def get(self, context_dict, request):
        raise NotImplementedError("AjaxAction.get() should be implemented by subclass.")
    
    def post(self, context_dict, request):
        raise NotImplementedError("AjaxAction.post() should be implemented by subclass.")


#---------------------------------------------------------------------------------------------------
# AJAX actions for resto sections
#---------------------------------------------------------------------------------------------------


class RestoSection(AjaxAction):
    
    def __init__(self, uid):
        self.__uid = uid
    
    def fetch_resto(self, context_dict):
        if "resto" not in context_dict:
            resto = Resto.gql("WHERE uid=:uid", uid=self.__uid).get()
            context_dict["resto"] = resto
        else:
            resto = context_dict.get("resto")
        if resto is None:
            raise AjaxError("Failed to get resto by uid '%s'." % self.__uid)
        else:
            return resto

    def get(self, context_dict, request):
        self.fetch_resto(context_dict)
        return True

    def post(self, context_dict, request):
        raise AjaxException("This AJAX action does not support POST request.")


class RestoNamesSection(RestoSection):

    def __init__(self, uid):
        super(RestoNamesSection, self).__init__(uid)
    
    def post(self, context_dict, request):
        resto = super(RestoNamesSection, self).fetch_resto(context_dict)
        resto.name = utils.get_param(request.POST, "name")
        resto.aka  = utils.get_param(request.POST, "aka")
        resto.put()
        return True


class RestoLogoSection(RestoSection):

    def __init__(self, uid):
        super(RestoLogoSection, self).__init__(uid)
    
    def post(self, context_dict, request):
        resto = super(RestoLogoSection, self).fetch_resto(context_dict)
        context_dict["error"] = "Not implemented yet!"
        return True


class RestoDescSection(RestoSection):

    def __init__(self, uid):
        super(RestoDescSection, self).__init__(uid)
    
    def post(self, context_dict, request):
        resto = super(RestoDescSection, self).fetch_resto(context_dict)
        resto.desc = utils.get_param(request.POST, "desc")
        resto.put()
        return True


class RestoAddressSection(RestoSection):

    def __init__(self, uid):
        super(RestoAddressSection, self).__init__(uid)
    
    def post(self, context_dict, request):
        resto = super(RestoAddressSection, self).fetch_resto(context_dict)
        resto.address   = utils.get_param(request.POST, "address")
        resto.post_code = utils.get_param(request.POST, "post_code")
        resto.city      = utils.get_param(request.POST, "city")
        resto.put()
        return True


class RestoContactSection(RestoSection):

    def __init__(self, uid):
        super(RestoContactSection, self).__init__(uid)
    
    def post(self, context_dict, request):
        resto = super(RestoContactSection, self).fetch_resto(context_dict)
        resto.website = utils.get_param(request.POST, "website")
        resto.email   = utils.get_param(request.POST, "email")
        resto.tel_1   = utils.get_param(request.POST, "tel_1")
        resto.tel_2   = utils.get_param(request.POST, "tel_2")
        resto.put()
        return True


class RestoRatingSection(RestoSection):

    def __init__(self, uid):
        super(RestoRatingSection, self).__init__(uid)


class RestoTagsSection(RestoSection):

    def __init__(self, uid):
        super(RestoTagsSection, self).__init__(uid)
    
    def post(self, context_dict, request):
        resto = super(RestoTagsSection, self).fetch_resto(context_dict)
        resto.tags = utils.split_string(utils.get_param(request.POST, "tags"))
        resto.put()
        return True


class RestoBestDishesSection(RestoSection):

    def __init__(self, uid):
        super(RestoBestDishesSection, self).__init__(uid)
    
    def post(self, context_dict, request):
        resto = super(RestoBestDishesSection, self).fetch_resto(context_dict)
        resto.best_dishes = utils.split_string(utils.get_param(request.POST, "best_dishes"))
        resto.put()
        return True


class RestoMapSection(RestoSection):

    def __init__(self, uid):
        super(RestoMapSection, self).__init__(uid)
    
    def get(self, context_dict, request):
        context_dict["map_canvas_id"] = utils.generate_random_id()
        return super(RestoMapSection, self).get(context_dict, request)
    
    def post(self, context_dict, request):
        resto = super(RestoMapSection, self).fetch_resto(context_dict)
        latitude  = float(utils.get_param(request.POST, "latitude"))
        longitude = float(utils.get_param(request.POST, "longitude"))
        resto.set_geo_location(latitude, longitude)
        resto.put()
        context_dict["map_canvas_id"] = utils.generate_random_id()
        return True


class RestoCommentsSection(RestoSection):

    def __init__(self, uid):
        super(RestoCommentsSection, self).__init__(uid)
    
    def get(self, context_dict, request):
        COMMENTS_PER_PAGE = 10
        page  = utils.get_param(request.GET, "page")
        resto = super(RestoCommentsSection, self).fetch_resto(context_dict)
        query = RestoComment.gql("WHERE ANCESTOR IS :resto ORDER BY post_date DESC", resto=resto)
        comments = utils.EntityPage(query, per_page=COMMENTS_PER_PAGE, number=page)
        context_dict["comments"] = comments
        return True


class RestoPhotosSection(RestoSection):

    def __init__(self, uid):
        super(RestoPhotosSection, self).__init__(uid)


class RestoFooterSection(RestoSection):

    def __init__(self, uid):
        super(RestoFooterSection, self).__init__(uid)


#---------------------------------------------------------------------------------------------------
# Mappings from resto section name to AJAX action class
#---------------------------------------------------------------------------------------------------


RESTO_SECTION_MAPPINGS = { "resto_names"       : RestoNamesSection,
                           "resto_logo"        : RestoLogoSection,
                           "resto_desc"        : RestoDescSection,
                           "resto_address"     : RestoAddressSection,
                           "resto_contact"     : RestoContactSection,
                           "resto_rating"      : RestoRatingSection,
                           "resto_tags"        : RestoTagsSection,
                           "resto_best_dishes" : RestoBestDishesSection,
                           "resto_map"         : RestoMapSection,
                           "resto_comments"    : RestoCommentsSection,
                           "resto_photos"      : RestoPhotosSection,
                           "resto_footer"      : RestoFooterSection,
                         }



